<?php

namespace Admin\Controller;

use Admin\Model\RoleModel;
use Admin\Model\UserModel;
use Think\Controller;
use Think\Verify;

class LoginController extends BaseController
{
    // 登录页面
    public function index()
    {
        return $this->display('/login');
    }

    // 登录操作
    public function doLogin()
    {
        $userName = $_POST['user_name'];
        $password =$_POST["password"];
        $code =$_POST["code"];



        $verify = new Verify();
/*        if (!$verify->check($code)) {
            return $this->formatjson(msg(-2, '', '验证码错误'));
        }*/

        $userModel =   new UserModel();
        $hasUser = $userModel->findUserByName($userName);
        if(empty($hasUser)){
            return $this->formatjson(msg(-3, '', '管理员不存在'));
        }

        if(md5($password) != $hasUser['password']){
            return $this->formatjson(msg(-4, '', '密码错误'));
        }

        if(1 != $hasUser['status']){
            return $this->formatjson(msg(-5, '', '该账号被禁用'));
        }

        // 获取该管理员的角色信息
        $roleModel = new RoleModel();
        $info = $roleModel->getRoleInfo($hasUser['role_id']);

        session('username', $userName);
        session('id', $hasUser['id']);
        session('role', $info['role_name']);  // 角色名
        session('rule', $info['rule']);  // 角色节点
        session('action', $info['action']);  // 角色权限

        // 更新管理员状态
        $param = [
            'login_times' => $hasUser['login_times'] + 1,
            'last_login_ip' =>$_REQUEST ['ip'],  //request()->ip(),
            'last_login_time' => time()
        ];
        $res = $userModel->updateStatus($param, $hasUser['id']);
        if(1 != $res['code']){
            return $this->formatjson(msg(-6, '', $res['msg']));
        }

        // ['code' => 1, 'data' => U('index/index'), 'msg' => '登录成功']
        return $this->formatjson(msg(1, U('index/index'), '登录成功'));
    }

    // 验证码
    public function checkVerify()
    {
        $verify = new Verify();
        $verify->imageH = 32;
        $verify->imageW = 100;
        $verify->length = 4;
        $verify->useNoise = false;
        $verify->fontSize = 14;
        return $verify->entry();
    }

    // 退出操作
    public function loginOut()
    {
        session('username', null);
        session('id', null);
        session('role', null);  // 角色名
        session('rule', null);  // 角色节点
        session('action', null);  // 角色权限

        $this->redirect('index');
    }
}
?>